<?php
	class AdsCampaign extends LilAdsAppModel {
		var $name = 'AdsCampaign';
		var $validate = array(
			'title' => array('rule'=>array('minLength', '1'), 'required'=>true),
			'priority' => array('format' => array('rule' => array('custom', '/^(1|2|3)$/'))),
			'limit_views' => array('rule'=>'numeric', 'allowEmpty'=>true),
			'limit_clicks' => array('rule'=>'numeric', 'allowEmpty'=>true),
		);
		var $hasMany = array('AdsBanner'=>array('className'=>'LilAds.AdsBanner', 'foreignKey'=>'ads_campaign_id'));

		function conditions(&$params) {
			$filters = array('active', 'priority');
			
			/*uses('session');
			$s = new CakeSession();*/
			
			if (isset($params['filter']) && $params['filter'] == 'all') {
				// remove possibly set filters if there is filter all
				$params = array_diff_key($params, array_flip($filters));
				unset($params['filter']);
			} else if (array_intersect_key((array)$params, array_flip($filters))==array()) {
				// load params from session
				//$params = am((array)$params, (array)$s->read('Filter.Campaign'));
			}

			// defaults
			if (!isset($params['active'])) $params['active'] = 1;
			
			// filters
			$conditions = array();
			if (isset($params['active']) && $params['active']!=='NULL') {
				$conditions[$this->escapeField('active')] = (boolean)$params['active'];
			}

			if (isset($params['priority']) && $params['priority']!=='NULL') {
				if ($params['priority'] >= 1 && $params['priority'] <= 3) {
					$conditions[$this->escapeField('priority')] = (int)$params['priority'];
				} else {
					$conditions[$this->escapeField('priority')] = 2;
				}
			}
			
			// save params to session or cookie
			//$s->write('Filter.Campaign', array_intersect_key((array)$params, array_flip($filters)));
			
			// allow only certain params
			//$params = array_intersect_key((array)$params, array_flip(am(array('sort', 'direction', 'limit'), $filters)));
			return $conditions;
		}

		function activate($id=null) {
			if (is_numeric($id) && $this->read(null, $id)) {
				return $this->saveField('active', 1);
			}
			return false;
		}
		
		function refresh($id=null) {
			if (is_numeric($id) && $this->read(null, $id)) {
				App::import('Model', 'LilAds.AdsAction');
				$action = new AdsAction(); $params = array('ads_campaign_id'=>$id);
				$stat = $action->getStats($params, 0);
				if (!empty($stat)) {
					return $this->save(array('clicks'=>$stat[0][0]['clicks'], 'views'=>$stat[0][0]['views']));
				} else {
					return true;
				}
			}
			return false;
		}
	}
?>